<script setup>
import { ref, onMounted, reactive } from 'vue';
import { 
  Search, 
  Delete, 
  Edit, 
  More, 
  Refresh, 
  Ship, 
  Check, 
  Close 
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import request from '@/utils/request.js';

// 订单数据
const orderList = ref([]);
const total = ref(0);
const loading = ref(false);
const orderDetailVisible = ref(false);
const currentOrder = ref({});
const currentOrderItems = ref([]);
const shipDialogVisible = ref(false);
const selectedRider = ref('');
const riderList = ref([]);

// 分页和筛选参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: '',
  orderNo: '',
});

// 状态选项
const statusOptions = [
  { value: '', label: '全部' },
  { value: 'PENDING_PAYMENT', label: '待付款' },
  { value: 'PAID', label: '已付款' },
  { value: 'SHIPPED', label: '已发货' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' },
];

// 状态显示
const statusMap = {
  'PENDING_PAYMENT': { label: '待付款', type: 'warning' },
  'PAID': { label: '已付款', type: 'success' },
  'SHIPPED': { label: '已发货', type: 'primary' },
  'COMPLETED': { label: '已完成', type: 'success' },
  'CANCELLED': { label: '已取消', type: 'info' },
};

// 加载订单列表
const getOrders = async () => {
  loading.value = true;
  try {
    const { data: res } = await request.get('/order/status', {
      params: {
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize,
        status: queryParams.status,
        orderNo: queryParams.orderNo,
      },
    });
    orderList.value = res.list || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取订单列表失败', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 查看订单详情
const viewOrderDetail = async (orderNo) => {
  try {
    const { data: res } = await request.get(`/order/detail/${orderNo}`);
    currentOrder.value = res.order || {};
    currentOrderItems.value = res.items || [];
    orderDetailVisible.value = true;
  } catch (error) {
    console.error('获取订单详情失败', error);
    ElMessage.error('获取订单详情失败');
  }
};

// 处理订单发货
const handleShip = (order) => {
  currentOrder.value = order;
  getRiders();
  shipDialogVisible.value = true;
};

// 获取可用骑手列表
const getRiders = async () => {
  try {
    const { data: res } = await request.get('/rider/available');
    riderList.value = res || [];
  } catch (error) {
    console.error('获取骑手列表失败', error);
    ElMessage.error('获取骑手列表失败');
  }
};

// 确认发货
const confirmShip = async () => {
  if (!selectedRider.value) {
    ElMessage.warning('请选择骑手');
    return;
  }

  try {
    await request.put('/order/ship', {
      orderId: currentOrder.value.id,
      riderId: selectedRider.value,
    });
    ElMessage.success('订单发货成功');
    shipDialogVisible.value = false;
    getOrders(); // 刷新订单列表
  } catch (error) {
    console.error('订单发货失败', error);
    ElMessage.error('订单发货失败');
  }
};

// 重置查询条件
const resetQuery = () => {
  queryParams.status = '';
  queryParams.orderNo = '';
  queryParams.pageNum = 1;
  getOrders();
};

// 处理分页变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getOrders();
};

const handleCurrentChange = (current) => {
  queryParams.pageNum = current;
  getOrders();
};

// 初始化
onMounted(() => {
  getOrders();
});

// 添加时间格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit',
    second: '2-digit'
  });
};
</script>

<template>
  <div class="order-management">
    <el-card class="order-card">
      <template #header>
        <div class="card-header">
          <span class="header-title">订单管理</span>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="订单状态" style="width: 250px;">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getOrders">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 订单列表 -->
      <el-table
        v-loading="loading"
        :data="orderList"
        border
        style="width: 100%"
      >
        <el-table-column label="订单编号" prop="orderNo" width="220" />
        <el-table-column label="用户信息" width="340">
          <template #default="{ row }">
            <div>
              <span style="margin-right: 30px;">账号: {{ row.username }}</span>
              <span style="margin-right: 30px;">昵称: {{ row.nickname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" prop="actualAmount" width="110">
          <template #default="{ row }">
            <span>¥{{ row.actualAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品数量" prop="itemCount" width="100">
          <template #default="{ row }">
            <span>{{ row.itemCount || 0 }}件</span>
          </template>
        </el-table-column>
        <el-table-column label="支付方式" prop="paymentType" width="110">
          <template #default="{ row }">
            <span>{{ row.paymentType === 'ONLINE' ? '在线支付' : '货到付款' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" prop="status" width="100">
          <template #default="{ row }">
            <el-tag :type="statusMap[row.status]?.type">
              {{ statusMap[row.status]?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="createTime" width="300">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="155">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              text
              @click="viewOrderDetail(row.orderNo)"
            >
              详情
            </el-button>
            <el-button
              v-if="row.status === 'PAID' || (row.status === 'PENDING_PAYMENT' && row.paymentType === 'CASH')"
              type="success"
              size="small"
              text
              @click="handleShip(row)"
            >
              发货
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="700px"
    >
      <el-descriptions title="订单信息" :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="statusMap[currentOrder.status]?.type">
            {{ statusMap[currentOrder.status]?.label }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户信息">
          <div>账号: {{ currentOrder.username }}</div>
          <div>昵称: {{ currentOrder.nickname }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="支付方式">
          {{ currentOrder.paymentType === 'ONLINE' ? '在线支付' : '货到付款' }}
        </el-descriptions-item>
        <el-descriptions-item label="订单总金额">¥{{ currentOrder.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount }}</el-descriptions-item>
        <el-descriptions-item label="商品总数量">{{ currentOrder.itemCount || 0 }}件</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ formatDate(currentOrder.paymentTime) }}</el-descriptions-item>
        <el-descriptions-item label="发货时间">{{ formatDate(currentOrder.shippingTime) }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ formatDate(currentOrder.completionTime) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '无' }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">收货信息</el-divider>
      
      <el-descriptions :column="1" border v-if="currentOrder.addressInfo">
        <el-descriptions-item label="收货人">{{ currentOrder.addressInfo.receiverName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.addressInfo.receiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ currentOrder.addressInfo.detailedAddress }}</el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="center">商品信息</el-divider>
      
      <el-table :data="currentOrderItems" border style="width: 100%">
        <el-table-column label="商品名称" prop="commodityName" min-width="150" />
        <el-table-column label="单价" prop="commodityPrice" width="100">
          <template #default="{ row }">
            <span>¥{{ row.commodityPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="quantity" width="70" />
        <el-table-column label="小计" prop="subtotal" width="100">
          <template #default="{ row }">
            <span>¥{{ row.subtotal }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 订单发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form label-width="80px">
        <el-form-item label="订单编号">
          {{ currentOrder.orderNo }}
        </el-form-item>
        <el-form-item label="选择骑手">
          <el-select v-model="selectedRider" placeholder="请选择骑手" style="width: 100%">
            <el-option
              v-for="rider in riderList"
              :key="rider.id"
              :label="`${rider.id} - ${rider.userId}(评分:${rider.rating})`"
              :value="rider.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.order-management {

}

.order-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>